%-------------------------------------------------------------------------
% Subroutine: Figures showing historical decomposition
%
% Estimation Codes for State-Level Results in  
% Ben-David, Itzhak, Sebastian Weber, and Pascal Towbin 
% "Inferring Expectations from Observables: Evidence from the Housing Market" 
% Review of Economics and Statistics
% ------------------------------------------------------------------------ 

sandstates={'FL';'NV';'AZ';'CA'};
sand_selec=[];
for ss=1: size(sandstates,1)
xx=find(strcmp(state_vec, sandstates{ss}));
sand_selec=[sand_selec xx];
end
no_sand_selec=[];
for ss=1:size(state_vec,1)
    if sand_selec~=ss;
        no_sand_selec=[no_sand_selec ss];
    end
end

 
colorcode=[0 0.5 0; 0 0 1; 0 1 1; 1 0 0;0.4 0.4 0.4;];

figurename={'Figure 5b Sand states', 'Figure 5a All excl sand states'};

%% SAND STATES
for qq=1:2
if qq==1
    select=sand_selec;
else
    select=no_sand_selec;
end


histirf_cent=mean(histirf(:,:,:,select),4);
histempt_cent=mean(histempt(:,:,:,select),4);
realdata=squeeze(mean(coll_realdata(:,:,select),3));

hist_diff(:,qq)=squeeze(histirf_cent(n_decomp,peakdate,:)-histirf_cent(n_decomp,troughdate,:));
hist_diff_rel(:,qq)=squeeze(histirf_cent(n_decomp,peakdate,:)-histirf_cent(n_decomp,troughdate,:))/sum(squeeze(histirf_cent(n_decomp,peakdate,:)-histirf_cent(n_decomp,troughdate,:)));


colorcode2=[0.2 0.2 0.2;  0 0.7 0; 0 0 1; 0 1 1; 1 0 0; 0.5 0.5 0.5];

figure('Name',[figurename{qq} ' : State-level contribution of shocks to price evolution'],'Units','centimeters','Position',[5 5 18 14])
set(gcf, 'Name',[figurename{qq} ' : State-level contribution of shocks to price evolution'],'NumberTitle','off') 
 bardata=[squeeze(histirf_cent(n_decomp,end+p-gapstart:end,1:no_str)),squeeze(sum((histirf_cent(n_decomp,end+p-gapstart:end,no_str+1:n_var)'),2)) ];
[hP, hB]=barExtended(gca,bardata,'FaceColor','flat'); hold on, ...
barExtenColor(colorcode, hP, hB);
h1=plot(1:size(timestr,1),  squeeze(realdata(n_decomp,end+p-gapstart:end))-squeeze(histempt_cent(n_decomp,end+p-gapstart:end,2)),'LineStyle', '-', 'LineWidth',1.5, 'Color','r'); hold on, ...
x = size(timestr,1)-5;
legend([hP h1],[shockname2, {'Residual','House price'}],'Location','NorthWest')      
legend('boxoff')  
set(gca, 'XTick', spacing, 'XTickLabel', timestr(spacing));    
xlim([1 gapstart])
ylim([-30 60])

%% Save data to excel
if savedata==1
Contrib_legend=[shockname2, {'Residual','House Price'}];
linedata=squeeze(realdata(n_decomp,end+p-gapstart:end))-squeeze(histempt_cent(n_decomp,end+p-gapstart:end,2));
Contrib=[bardata,  linedata'];
xlswrite( fullfile(outputfolder, [figurename{qq} '.xlsx']),[{'Date'}, Contrib_legend; num2cell(timestr), num2cell(Contrib)], [ name{qq}],'B2');
end
end

